package com.spring.springboot.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Throwables;
import com.spring.springboot.entity.FileInfo;
import com.spring.springboot.mapper.FileInfoMapper;
import com.spring.springboot.sys.base.ServiceException;
import com.spring.springboot.sys.core.constant.BusinessConstant;
import com.spring.springboot.sys.core.enums.ResponseCodeEnum;
import com.spring.springboot.sys.core.model.DeleteFileInfoParam;
import com.spring.springboot.sys.core.model.Result;
import com.spring.springboot.sys.core.model.UploadResponse;
import com.spring.springboot.sys.util.MinioUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 宋义州
 * @date 2022-07-25  23:58
 * @description 文件上传控制器
 */
@Slf4j
@Api(tags = "文件上传")
@RestController
@RequestMapping("/api/file")
public class UploadFileController {

    @Resource
    private FileInfoMapper fileInfoMapper;

    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传")
    @Operation(security = {@SecurityRequirement(name = "Authorization")})
    @ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    public Result uploadFile(@RequestPart(value = "file", required = false) MultipartFile file) {
        try {
            log.info("文件上传开始!}");
            long startTime = System.currentTimeMillis();
            if (null == file || file.isEmpty() || file.getSize() == 0) {
                log.info("文件为空!}");
                throw new ServiceException(400, "文件为空");
            }
            //上传
            UploadResponse uploadResponse = MinioUtils.uploadFile(file, LocalDate.now().format(DateTimeFormatter.ofPattern(BusinessConstant.DateFormat.DATE_FORMAT)));
            if (Objects.isNull(uploadResponse)) {
                throw new ServiceException(400, "文件上传失败");
            }
            log.info("文件上传结束 response:{}，耗时:{}", uploadResponse, (System.currentTimeMillis() - startTime));
            return Result.success("上传成功！", uploadResponse);
        } catch (
                Exception e) {
            log.info("文件上传失败 Exception：{}", Throwables.getStackTraceAsString(e));
            throw new ServiceException(400, "文件上传失败");
        }
    }

    @PostMapping("/deleteFile")
    @ApiOperation(value = "删除文件")
    @Operation(security = {@SecurityRequirement(name = "Authorization")})
    @ApiImplicitParam(name = "url", value = "文件信息", required = true, paramType = "body", dataType = "DeleteFileInfoParam", dataTypeClass = DeleteFileInfoParam.class)
    public Result deleteFile(@RequestBody DeleteFileInfoParam fileInfoParam) {
        Long id = fileInfoParam.getId();
        String urlPath = fileInfoParam.getUrlPath();
        List<String> strings = Arrays.asList(urlPath.split("/"));
        List<String> collect = strings.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        FileInfo fileInfo = fileInfoMapper.selectOne(new LambdaQueryWrapper<FileInfo>()
                .eq(FileInfo::getId, id)
                .eq(FileInfo::getDelFlag, BusinessConstant.DeleteStatus.NO_DELETE)
                .eq(FileInfo::getUrlPath, urlPath));
        if (ObjectUtils.isEmpty(fileInfo)) {
            throw new ServiceException(ResponseCodeEnum.RESOURCE_DELETE);
        }
        // 标记位改为已删除
        fileInfo.setDelFlag(BusinessConstant.DeleteStatus.DELETE);
        // 更新数据
        fileInfoMapper.updateById(fileInfo);
        log.info("----------删除文件---------->{}", collect);
        return Result.success("文件删除成功!");
    }

    public static void main(String[] args) {
        String s = "http://101.132.132.177:9527/2022-07-22/2022-07-22_1658473666032_2022-07-22_123.jpg";
        List<String> strings = Arrays.asList(s.split("/"));
        List<String> collect = strings.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        System.out.println(collect);
    }
}
